﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebSockets.modules
{
    internal class WebSocketServer
    {
        public event EventHandler<WebSocketMessageEventArgs> WebSocketMessageReceived;

        private HttpListener _httpListener;

        public List<WebSocket> WebSocketList = new List<WebSocket>();

        public async Task Start()
        {
            _httpListener = new HttpListener();
            _httpListener.Prefixes.Add("http://localhost:65000/");
            _httpListener.Start();

            while (true)
            {
                var context = await _httpListener.GetContextAsync();
                if (context.Request.IsWebSocketRequest)
                {
                    var webSocketContext = await context.AcceptWebSocketAsync(null);

                    WebSocketList.Add(webSocketContext.WebSocket);

                    await HandleWebSocketConnection(webSocketContext.WebSocket);
                }
                else
                {
                    context.Response.StatusCode = 400;
                    context.Response.Close();
                }
            }
        }


        private async Task HandleWebSocketConnection(WebSocket webSocket)
        {
            var buffer = new byte[1024];
            var receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            while (!receiveResult.CloseStatus.HasValue)
            {
                var message = Encoding.UTF8.GetString(buffer, 0, receiveResult.Count);
                //var response = $"wpf sent: {message}";
                //var responseBuffer = Encoding.UTF8.GetBytes(response);
                //await webSocket.SendAsync(new ArraySegment<byte>(responseBuffer), WebSocketMessageType.Text, true, CancellationToken.None);

                // 创建事件参数对象
                var args = new WebSocketMessageEventArgs(webSocket, message);
                // 检查是否有订阅者，如果有则触发事件
                WebSocketMessageReceived?.Invoke(this, args);

                receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }

            await webSocket.CloseAsync(receiveResult.CloseStatus.Value, receiveResult.CloseStatusDescription, CancellationToken.None);
        }

        public async Task SendAsync(WebSocket webSocket,string message)
        {
            var response = $"wpf sent: {message}";
            var responseBuffer = Encoding.UTF8.GetBytes(response);
            await webSocket.SendAsync(new ArraySegment<byte>(responseBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
        }
    }


    // 自定义事件参数类，用于传递 WebSocket 和 string 内容
    public class WebSocketMessageEventArgs : EventArgs
    {
        public WebSocket WebSocket { get; }
        public string Message { get; }

        public WebSocketMessageEventArgs(WebSocket webSocket, string message)
        {
            WebSocket = webSocket;
            Message = message;
        }
    }
}
